package com.example.service.impl;

import com.example.dao.EsMovieRepository;
import com.example.dao.MovieDao;
import com.example.pojo.movies.Movie;
import com.example.service.MovieService;
import com.example.service.EsMovieService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
public class EsMovieServiceImpl implements EsMovieService {
    @Autowired
    MovieDao movieDao;
    @Autowired
    EsMovieRepository movieRepository;

    @Autowired
    HashMap<String, Integer> dict;

    @Override
    public int importAll() {
        List<Movie> MovieList = movieDao.selectAll();
        Iterable<Movie> esMovieIterable = movieRepository.saveAll(MovieList);
        Iterator<Movie> iterator = esMovieIterable.iterator();
        int result = 0;
        while (iterator.hasNext()) {
            result++;
            iterator.next();
        }
        return result;
    }

    @Override
    public void delete(Long id) {
        movieRepository.deleteById(id);
    }

    @Override
    public Movie create(Long id) {
        Movie result = null;
        Movie movie = movieDao.selectById(id.intValue());
        if (movie != null) {
            result = movieRepository.save(movie);
        }
        return result;
    }



    @Override
    public Page<Movie> findByNameOrStoryline(String keyword, Integer pageNum, Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNum, pageSize);
        return movieRepository.findByNameOrStoryline(keyword, keyword, pageable);
    }

//    @Override
//    public Map<String, Integer> searchPage() {
//        //聚合
//        String aggName = "storyline";
//        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
//        //聚合
//        queryBuilder.addAggregation(AggregationBuilders.terms(aggName).field("storyline"));
//        //查询并返回带聚合结果
//        AggregatedPage<Anime> result = elasticsearchTemplate.queryForPage(queryBuilder.build(), Anime.class);
//        //解析聚合
//        Aggregations aggregations = result.getAggregations();
//        //获取指定名称的聚合
//        StringTerms terms = aggregations.get(aggName);
//        //获取桶
//        List<StringTerms.Bucket> buckets = terms.getBuckets();
//        //遍历打印
//        Map<String, Integer> map = new HashMap<>();
//        for (StringTerms.Bucket bucket : buckets) {
//            if (dict.get(bucket.getKeyAsString().replace(" ", "")) == null) continue;
//            map.put(bucket.getKeyAsString(), (int) bucket.getDocCount());
//            System.out.println("key = " + bucket.getKeyAsString());
//            System.out.println("DocCount = " + bucket.getDocCount());
//        }
//        return map;
//    }

}
